﻿using System;
using System.Collections.Generic;

using System.Text;
using repliback4.Misc;
using Tools.Debugging;
using repliback4.Net.ServerSide;

namespace repliback4.Net.Protocol.InfoQueryHandling {
    public class InfoQueryHandlerManager<T,Q,C> where T : InfoQueryHandler<Q> where Q:QueryFrom<C> {
        protected Dictionary<String, T> table = new Dictionary<string, T>( );


        public void Add ( String query, T handler ) {
            Logger.Debug( this, "adding IQ handler for {0}", query );
            this.table.Add( query, handler );
        }

        public void Add ( Type type, T handler ) {
            this.table.Add( type.GetReplibackTagName( ), handler );
        }

        public void Handle ( Q item ) {
            T handler;
            //InfoQueryHandler handler;
            String queryName = item.Query.Query.GetType( ).GetReplibackTagName( );
            Logger.Debug( this, "handling query {0}", queryName );

            if ( this.table.TryGetValue( queryName, out handler ) ) {

                try {
                    handler.Handle( item );
                } catch ( Exception e ) {
                    Logger.Exception( this, "ServerInfoQueryHandlerManager Handler exception", e );
                    this.HandleHandlerException( item );
                }
            } else {
                this.HandleNotImplemented( item );
            }
        }



        private void HandleHandlerException ( Q item ) {
            Logger.Debug( this, "will send general-error" );
        }

        private void HandleNotImplemented ( Q item ) {
            Logger.Debug( this, "will send feature-not-implemented" );

            //<iq type="error" id="aac1a" to="sszymbor@gmail.com/gTalk-thea349E3814" >
            //<query xmlns="jabber:iq:kot"/>
            //<error type="cancel" code="501" >
            //<feature-not-implemented xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
            //</error>
            //</iq>             

        }
    }
}
